// pages/index_detail/index_detail.js
var app = getApp();//引用app.js
var commonURL = app.data.baseURL;
var animation = wx.createAnimation({
  duration: 600,  //动画持续时间，单位ms，默认值 400
  timingFunction: 'linear'//linear  动画一直较为均匀
});
Page({
  data: {
    Img: '',
    openSettingBtnHidden: false,
    isShow: false,
    isImg: false,
    getShow: false,
    isCanvas: false,
    qrcodeImg: '',
    issetting: false,
    "price": {
      dandu: "",
      tuangou: "",
      num: ""
    },
    "guige": {
      img: "",
      price: "0.00",
      list: [
        {
          id: "",
          name: ""
        }
      ]
    },
    "guigeOptions": [
      // {
      //   costprice:"0.03",
      //   id:"8697",
      //   marketprice:"0.01",
      //   productprice:"0.02",
      //   specs:"4110",
      //   stock:"11105",
      //   thumb:"",
      //   title:"黄"
      // }
    ],
    "currentItem": [
      // {
      //   title:"",
      //   item:"",
      // }
    ],
    "disabledGuige": "none",
    "animation": "",//规格弹窗
    "imgUrls": [],
    "detail": {
      id: "",
      title: "",
      shichangprice: "",
      salenum: "",
      unit: "",
      img: "",
      kucun: "",
      selltype: "",
      deliverytype: ""
    },
    "navTab": ["图文详情", "商品属性"],
    "currentNavtab": "0",
    "likes": [
      // {
      //   img:"../../images/index/detail1.jpg",
      //   title:"苹果1苹果苹果苹果苹果苹果",
      //   price:"28.00"
      // }
    ],
    "close": "none",//关闭图标属性
    "xiangqing": {},
    "shuxing": [
      // {
      //   text1:"11111",
      //   text2:"22222"
      // }
    ]
  },
  onLoad: function (options) {
    var that = this;

    if (options.xiaoqu) { //判断是否听过分享链接进入的
      wx.setStorage({
        key: 'xiaoqu',
        data: JSON.parse(options.xiaoqu),
        success: function (res) {
          console.log('设置成功')
        },
        fail: function (res) {
          console.log('设置失败')
        }
      })
    }
    //判断是不是扫码进来
    if (decodeURIComponent(options.scene) !== 'undefined') {
      let scene = decodeURIComponent(options.scene);
      let indexid = options.scene.split("&")[0];
      let arearid = options.scene.split('&')[1];
      wx.request({
        url: commonURL + 'op=shop_area',
        data: {
          uniacid: app.data.GZHid,
          areaid: arearid,
          dev: 1
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res);
          var casArray = [];
          var item = {};
          var obj = {};
          console.log(res.data.length == 0)
          if (res.data.length == 0) {
            wx.showModal({
              title: '提示',
              content: '获取团长失败,请重新选择团长',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '../regimental/regimental',
                  })
                }
              }
            })
          } else {
            item['name'] = res.data[0].name,
              item['id'] = res.data[0].id,
              item['tzname'] = res.data[0].commander.name,
              item['join_hotline'] = res.data[0].join_hotline,
              item['merchant_entry'] = res.data[0].merchant_entry,
              item['avatar'] = res.data[0].commander.avatar,
              item['commanderTel'] = res.data[0].commander.mobile,
              item['address'] = res.data[0].address
            obj['name'] = res.data[0].name,
              obj['id'] = res.data[0].id,
              obj['item'] = item
            wx.setStorage({
              key: 'xiaoqu',
              data: obj,
            })
          }
        }
      })
      that.setData({
        indexid: indexid,
        arearid: areaid
      })
    } else {
      var indexid = options.id
      this.setData({
        indexid: indexid
      })
    }
    var that = this;
    var areaid = ''
    wx.getStorage({//获取小区地址
      key: 'xiaoqu',
      success: function (res) {
        console.log(res.data.item, "xiaoqu")
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
        areaid = res.data.item.id
        that.setData({
          areaid: areaid
        })
      },
      fail: function () {
        wx.navigateTo({
          url: '../cell_selection/cell_selection',
        })
      }
    })
    wx.getStorage({
      key: 'shareqrImg',
      success: function (res) {
        that.setData({
          qrCode: res.data
        })
      },
    })
    var likes = [];
    var imgUrls = [];
    var shuxing = [];
    var xiangqing = "";
    wx.request({//ajax加载商品详情
      url: commonURL + 'op=goods_detail_yh',
      data: {
        id: indexid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res.data,888888888);
        var data = res.data;
        if (data.advs.length == 0) {//获取轮播图片
          imgUrls.push(data.gimg);
        } else {
          for (var j = 0; j < data.advs.length; j++) {
            imgUrls.push(data.advs[j].thumb);
          }
        }
        if (data.params.length == 0) {
          shuxing = [{ text1: "暂无属性信息" }];
        } else {
          for (var i = 0; i < data.params.length; i++) {//获取属性信息
            var obj = {};
            obj["text1"] = data.params[i].title;
            obj["text2"] = data.params[i].value;
            shuxing.push(obj);
          }
        }
        if (data.gdesc == "") {
          (xiangqing = "暂无详情信息")
        } else {
          xiangqing = data.gdesc;
          that.setData({
            goodsdesc: that.escapeHtml(data.goodsdesc).replace(/\<img/gi, '<img style="max-width:100%;height:auto" '),
            xiangqing: that.escapeHtml(xiangqing).replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          })
        }
        Date.prototype.toLocaleString = function () {
          return this.getFullYear() + "/" + (this.getMonth() + 1) + "/" + this.getDate() + "/ " + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds();
        }
        if (data.ison == '1') {
          data.thistuan.map(item => {
            item.starttime = new Date(item.starttime * 1000).toLocaleString();
          })
        }
        that.saveStore(data.stores);
        that.setData({
          "imgUrls": imgUrls,
          "detail": {
            id: data.id,
            title: data.gname,
            shichangprice: data.mprice,
            salenum: data.salenum,
            unit: data.unit,
            img: data.share_image,
            share_image: data.share_image,
            yunfei: "",
            kuncun: data.gnum,
            selltype: data.selltype,
            deliverytype: data.deliverytype,
            hasoption: data.hasoption,
            weight: data.weight,
            isshow: data.isshow,
            gnum: data.gnum,
            shareGroup: data.thistuan,
            shareGroupSwitch: data.ison,                // 是否开启分享团 1:开 0:关
          },
          "price": {
            dandu: data.oprice,
            tuangou: data.gprice,
            num: data.groupnum
          },
          //"xiangqing":xiangqing,
          "shuxing": shuxing
        });
        //下载商品图片
        wx.downloadFile({
          url: that.data.detail.img,
          success: function (res) {
            that.setData({
              Img: res.tempFilePath,
            })
          }, fail: function (res) { console.log(res) }
        })
      }
    })
    wx.request({//ajax加载猜你喜欢
      url: commonURL + 'op=goods_rand',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res.data.list,2222222)
        if (res.data.list.length < 1) {
          return false
        }
        for (var i = 0; i < res.data.list.length; i++) {
          var obj = {};
          obj["id"] = res.data.list[i].id;
          obj["gimg"] = res.data.list[i].gimg;
          obj["title"] = res.data.list[i].gname;
          if (res.data.list[i].gprice != 0) {
            obj["price"] = res.data.list[i].gprice;
          } else {
            obj["price"] = res.data.list[i].oprice;
          }
          obj["selltype"] = res.data.list[i].selltype;
          likes.push(obj);
        }
        that.setData({
          "likes": likes
        })
      }
    })
    wx.request({
      url: app.data.baseURL + 'op=getWXACodeUnlimit',
      data: {
        appid: app.data.appid,
        secret: app.data.secret,
        uniacid: app.data.GZHid,
        opneid: app.data.openid,
        page: 'pages/index_detail/index_detail',
        dev: 1,
        scene: indexid + '&' + wx.getStorageSync('xiaoqu').id
      },
      success: function (res) {
        console.log(res)
        wx.downloadFile({
          url: res.data.data.surl,
          success: function (res) {
            that.setData({
              qrcodeImg11: res.tempFilePath,
              getShow: true
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },
  share: function () {
    var that = this;
    if (!this.data.shareImage) {
      this.setData({
        isShow: true,
        issetting: false,
        isCanvas: true
      })
      wx.showLoading({
        title: '正在生成图片...',
        mask: true,
      });
        let yOffset = 0;
        const goodsTitle = this.data.detail.title;
        let goodsTitleArray = [];
        //为了防止标题过长，分割字符串,每行15个
        for (let i = 0; i < goodsTitle.length / 15; i++) {
          if (i > 2) {
            break;
          }
          goodsTitleArray.push(goodsTitle.substr(i * 15, 15));
        }
        const tuangouPrice = this.data.price.tuangou;
        const danduPrice = this.data.price.dandu;
        const canvasCtx = wx.createCanvasContext('shareCanvas');
        //绘制背景
        canvasCtx.setFillStyle('white');
        canvasCtx.fillRect(0, 0, 390, 800);
        //绘制商品图片
        canvasCtx.drawImage(this.data.Img, 0, 0, 250, 150);
        //绘制商品标题
        yOffset = 100;
        canvasCtx.setFontSize(15);
        canvasCtx.setFillStyle('#333333');
        canvasCtx.setTextAlign('left');
        for (var i = 0; i < goodsTitleArray.length; i++) {
          canvasCtx.fillText(goodsTitleArray[i], 10, 180 + i * 20);
        }
        //绘制团购价
        if (danduPrice) {
          canvasCtx.setFontSize(18);
          canvasCtx.setFillStyle('#f9555c');
          canvasCtx.setTextAlign('left');
          canvasCtx.setFontSize(15);
          canvasCtx.setFillStyle('#f9555c');
          canvasCtx.setTextAlign('left');
          canvasCtx.fillText('团购价:¥' + tuangouPrice, 10, 210 + (goodsTitleArray.length - 1) * 20);
        }
        //绘制单独购买价格
        if (danduPrice) {
          const xOffset = (danduPrice.length / 2 + 1) * 24 + 50;
          canvasCtx.setFontSize(12);
          canvasCtx.setFillStyle('#999999');
          canvasCtx.setTextAlign('left');
          canvasCtx.fillText('单独购买:¥' + danduPrice, 10, 230 + (goodsTitleArray.length - 1) * 20);
        }
        //绘制底部提示文字
        canvasCtx.setFillStyle('#f9555c');
        canvasCtx.setTextAlign('left');
        canvasCtx.setFontSize(12);
        canvasCtx.setFillStyle('#999999');
        canvasCtx.setTextAlign('left');
        canvasCtx.fillText('长按识别图中的小程序码', 10, 300);
        //绘制二维码
      // canvasCtx.drawImage(that.data.qrCode, 150, 220, 80, 80);
      canvasCtx.drawImage(that.data.qrcodeImg11, 150, 220, 80, 80);
        setTimeout(function () {
          canvasCtx.draw(false, function () {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 250,
              height: 320,
              destWidth: 1000,
              destHeight: 1280,
              canvasId: 'shareCanvas',
              success: function (res) {
                that.setData({
                  shareImage: res.tempFilePath,
                  issetting: true,
                  ShowshareImg: res.tempFilePath
                })
                wx.hideLoading();
              },
              fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                  title: '错误，请稍后再试',
                })
              },
            })
          }
          );
        }, 1500)
    } else {
      var that = this;
      that.setData({
        isShow: true,
        isCanvas: false,
        isImg: true,
        issetting: true
      })
    }
  },
  //获取是否授权相册权限
  handleSetting: function (e) {
    let that = this;
    // 对用户的设置进行判断，如果没有授权
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '若不打开授权，则无法将图片保存在相册中！',
        showCancel: false
      })
      that.setData({
        saveImgBtnHidden: true,
        openSettingBtnHidden: true
      })
    } else {
      that.setData({
        saveImgBtnHidden: false,
        openSettingBtnHidden: false,
        issetting: true
      })
      wx.showModal({
        title: '提示',
        content: '您已授权，赶紧将图片保存在相册中吧！',
        showCancel: false
      })
    }
  },
  //保存图片到相册
  SaveShareImg: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.shareImage,
      success: function (res) {
        wx.showModal({
          title: '存图成功',
          content: '图片成功保存到相册了，去发朋友圈咯~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                isShow: false
              })
            }
          }
        })
      },
      fail: function (res) {
        if (res.errMsg != 'saveImageToPhotosAlbum:fail cancel') {
          wx.showModal({
            title: '授权提示',
            content: '请去授权，否则无法分享到朋友圈哦！',
            success: function (res) {
              if (res.cancel) {
                that.setData({
                  openSettingBtnHidden: false,
                  issetting: true
                })
              } else {
                //点击确定
                that.setData({
                  openSettingBtnHidden: true,
                  issetting: false
                })
              }
            },
            fail: function (res) {
              wx.showToast({
                title: '错误，请稍后再试',
              })
            }
          })
        }
      }
    })
  },
  //取消保存
  CancelShareImg: function () {
    this.setData({
      isShow: false
    })
  },
  switchTab: function (e) {
    this.setData({
      currentNavtab: e.currentTarget.dataset.idx
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    var that=this
    var xqname = ''
    var sname = ''
    var title = ''
    wx.getStorage({
      key: 'xiaoqu',
      success: function (res) {
        xqname = res.data.item.name
        wx.request({
          url: commonURL + 'op=uniacid_shop',
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res)
            // sname = res.data.set.tzname
            // title = sname + '-' + xqname
            wx.setNavigationBarTitle({ title: title });//设置title文字
          }
        })
        console.log(res.data.item, "xiaoqu")
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
      }
    })
    this.setData({
      disabledGuige: 'none'
    })
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  saveStore: function (data) {
    wx.setStorage({
      key: 'stores_tuan',
      data: data
    })
  },
  close: function (e) {
    this.setData({
      close: "none"
    })
  },
  open: function (e) {
    this.setData({
      close: "block"
    })
  },
  chooseGG: function (e) {//选择规格
    var that = this;
    var title = e.currentTarget.dataset.title;
    var options = that.data.guigeOptions;
    var currentItem = that.data.currentItem;
    var key = e.currentTarget.dataset.key;
    var guige = that.data.guige;
    currentItem[key].title = title;
    currentItem[key].item = e.currentTarget.dataset.index;
    that.setData({
      selectIndex: e.currentTarget.dataset.index
    })
    if (e.currentTarget.dataset.img) {
      guige.img = e.currentTarget.dataset.img
    }//如果规格图片存在，就替换图片
    for (var i = 0; i < options.length; i++) {
      for (var j = 0, ii = 0; j < currentItem.length; j++) {
        if (currentItem[j].title == "") {
          that.setData({
            "currentItem": currentItem,
            "guige": guige
          })
          return false;
        }
        var patt1 = new RegExp(currentItem[j].title);
        var result = patt1.test(options[i].title);
        result && ii++;
      }
      if (currentItem.length == ii) {
        var price = "";
        that.data.istuan ? price = options[i].marketprice : price = options[i].productprice;
        guige.price = price;
      }
    }
    that.setData({
      "currentItem": currentItem,
      "guige": guige
    })
  },
  onShareAppMessage: function () {//分享页面
    return {
      title: this.data.detail.title,
      path: '/pages/index_detail/index_detail?id=' + this.data.detail.id
    }
  },
  gotoIndexDetail: function (e) {
    var _selltype = e.currentTarget.dataset.selltype;
    if (_selltype == '0') {
      wx.redirectTo({
        url: '../index_only_detail/index_only_detail?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.redirectTo({
        url: '../index_detail/index_detail?id=' + e.currentTarget.dataset.id,
      })
    }
  },
  gotoBuyPage: function () {//规格弹窗，确定按钮
    var that = this;
    for (var i = 0; i < that.data.currentItem.length; i++) {
      if (that.data.currentItem[i].item == "-1") {//判断是否选中规格
        wx.showToast({
          title: '请选择规格',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
    }
    wx.removeStorage({ key: 'address' });
    for (var i = 0; i < that.data.guigeOptions.length; i++) {
      if (that.data.guigeOptions[that.data.selectIndex].cnum <= 0) {
        wx.showToast({
          title: '库存已被别人抢光,请稍后刷新页面再试',
          icon: 'none'
        })
        return;
      }
    }
    for (var jj = 0, title = ""; jj < that.data.currentItem.length; jj++) {
      title += ("+" + that.data.currentItem[jj].title);
    }
    var dataDetail = {
      id: that.data.detail.id,
      title: that.data.detail.title,
      price: that.data.guige.price,
      img: that.data.detail.img,
      selltype: that.data.detail.selltype,
      deliverytype: that.data.detail.deliverytype,
      weight: that.data.detail.weight,
      optionname: title.slice(1)
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    wx.navigateTo({
      url: (that.data.istuan) ? '../index_buy/index_buy?istuan=true' : '../index_buy/index_buy',
    })
  },
  gotoBuy_tuan: function (e) {
    var that = this;
    if (that.data.detail.hasoption == "1") {//有规格产品
      //弹出规格选择框
      that.ajaxGuige(that);//加载规格数据
      that.openGuige(that, true);
    } else {//无规格产品
      if (that.data.detail.kucun < 1) {
        wx.showToast({
          title: '库存不足,无法购买',
          icon: 'loading',
          duration: 2000
        })
      } else {
        that.tiaozhuanTuan();//调用跳转函数
      }
    }
  },
  gotoBuy_dan: function (e) {
    var that = this;
    if (that.data.detail.hasoption == "1") {//有规格产品
      //弹出规格选择框
      that.ajaxGuige(that);
      that.openGuige(that, false);
    } else {//无规格产品
      if (this.data.detail.kucun < 1) {
        wx.showToast({
          title: '库存不足,无法购买',
          icon: 'loading',
          duration: 2000
        })
      } else {
        that.tiaozhuanDan();//调用跳转函数
      }
    }
  },
  closeGuige: function () {
    var that = this;
    animation.height("0").step();
    that.setData({
      animation: animation.export() //关闭规格选择
    })
    setTimeout(function () {
      that.setData({ disabledGuige: "none" });
    }, 600)
  },
  openGuige: function (that, istuan) {//选择规格动画
    that.setData({
      disabledGuige: "block"
    });
    animation.height("540rpx").step();
    that.setData({
      animation: animation.export(),//输出动画
      istuan: istuan
    })
  },
  tiaozhuanDan: function () {//单买跳转函数
    wx.removeStorage({ key: 'address' });//清除缓存，修复地址不对应bug
    var dataDetail = {
      id: this.data.detail.id,
      title: this.data.detail.title,
      price: this.data.price.dandu,
      img: this.data.detail.img,
      selltype: this.data.detail.selltype,
      deliverytype: this.data.detail.deliverytype,
      weight: this.data.detail.weight
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    wx.navigateTo({
      url: '../index_buy/index_buy',
    })
  },
  tiaozhuanTuan: function () {//团购跳转函数
    wx.removeStorage({ key: 'address' });
    var dataDetail = {
      id: this.data.detail.id,
      title: this.data.detail.title,
      price: this.data.price.tuangou,
      img: this.data.detail.img,
      selltype: this.data.detail.selltype,
      deliverytype: this.data.detail.deliverytype,
      weight: this.data.detail.weight
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    wx.navigateTo({
      url: '../index_buy/index_buy?istuan=true',
    })
  },
  ajaxGuige: function (that) {
    var ajaxguige = wx.getStorageSync('guige');
    if (ajaxguige.id == that.data.detail.id) {//先判断该商品规格是否存在缓存中，否则ajax加载数据
      var data = ajaxguige.allspecs;
      var currentItem = [];
      for (var i = 0; i < data.length; i++) {
        currentItem.push({ title: "", item: "-1" });
      }
      if (data.length < 1) {
        return false
      }
      that.setData({
        guige: {
          img: that.data.detail.img,
          price: "0.00",
          list: data
        },
        guigeOptions: ajaxguige.options,
        currentItem: currentItem
      })
    } else {
      wx.request({
        url: commonURL + 'op=goods_guige',
        data: {
          id: that.data.detail.id,
          areaid: that.data.areaid
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          var data = res.data.allspecs;
          var currentItem = [];
          for (var i = 0; i < data.length; i++) {
            currentItem.push({ title: "", item: "-1" });
          }
          if (data.length < 1) {
            return false
          }
          that.setData({
            guige: {
              img: that.data.detail.img,
              price: "0.00",
              list: data
            },
            guigeOptions: res.data.options,
            currentItem: currentItem
          })
          // var dataguige = res.data;
          // dataguige.id = that.data.detail.id;
          // wx.setStorage({//把规格存储在缓存中
          //   key: 'guige',
          //   data: dataguige,
          // })
        }
      })
    }
  },
  gotoGroupDetail(e) {
    wx.navigateTo({
      url: '../mygroup_detail/mygroup_detail?tuan_id=' + e.currentTarget.dataset.id + '&g_id=' + e.currentTarget.dataset.g_id
    })
  },
  imageLoad: function (e) {
    var res = wx.getSystemInfoSync();
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      ratio = imgwidth / imgheight;
    this.setData({
      bannerHeight: res.windowWidth / ratio
    })
  },
  onSelected(e) {
    console.log(e)
    wx.previewImage({
      current: e.currentTarget.dataset.item,
      urls: this.data.imgUrls,
    })
  },
  escapeHtml: function (text) {
    var a = text.replace(/(\&lt;)/g, "<");
    var b = a.replace(/(\&gt;)/g, ">");
    var c = b.replace(/(\&amp;)/g, "\&");
    var d = c.replace(/(\&quot;)/g, "\"");
    //var e = d.replace(/(px)/g, "rpx");
    return d;
  }
})